package com.netty.pipeline;

import io.netty.channel.*;
import io.netty.channel.embedded.EmbeddedChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @author xl-9527
 * @since 2025/8/3
 **/
public class NettyPipelineDemo {

    private static final Logger log = LoggerFactory.getLogger(NettyPipelineDemo.class);

    public ChannelOutboundHandler getOutboundChannel(final String tag) {
        return new ChannelOutboundHandlerAdapter() {

            @Override
            public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
                log.info("OUTBOUND 【{}】 写的消息：{}", tag, msg);
                super.write(ctx, msg, promise);
            }
        };
    }

    public ChannelInboundHandler getInboundChannel(final String tag) {
        return new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
                log.info("INBOUND 【{}】 读的消息：{}", tag, msg);
                super.channelRead(ctx, msg);
            }
        };
    }

    public void run(final PipelineType pipelineType, final ChannelHandler... handlers) {
        final EmbeddedChannel channel = new EmbeddedChannel(handlers);
        switch (pipelineType) {
            case INBOUND:
                channel.writeInbound(UUID.randomUUID());
                break;
            case OUTBOUND:
                channel.writeOutbound(UUID.randomUUID());
                break;
        }
    }

    public enum PipelineType {
        INBOUND,
        OUTBOUND
    }
}
